/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBean;

import entities.Enseigne;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;  
  
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;  
import javax.faces.context.FacesContext;  
  
import javax.inject.Named;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.primefaces.event.map.OverlaySelectEvent;  
import org.primefaces.event.map.StateChangeEvent;
import org.primefaces.model.map.DefaultMapModel;  
import org.primefaces.model.map.LatLng;  
import org.primefaces.model.map.MapModel;  
import org.primefaces.model.map.Marker;  
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author Mic
 */
@Named(value = "mapBean")
@RequestScoped
public class MapBean implements Serializable {

    private static double latitude;
    private static double longitude;
    private static String descriptionPOI;
    private MapModel simpleModel;  
    private String coor;
      
    
  
    public MapBean() {  
        simpleModel = new DefaultMapModel();  
          
        //Shared coordinates  
        //LatLng coord1 = new LatLng(43.718933, 7.268076);  
        System.out.println("Const MapMbean "+descriptionPOI); 
        //String[] tabCoor = yahooLatLong().split("-");
        LatLng coord2 = new LatLng(latitude,longitude);
          
        //Basic marker  
        //simpleModel.addOverlay(new Marker(coord1, "Chez michel"));  
        simpleModel.addOverlay(new Marker(coord2, descriptionPOI));
    }

    public String getCoor() {
        return coor;
    }

    public void setCoor(String coor) {
        this.coor = coor;
    }
      
    public MapModel getSimpleModel() {  
        return simpleModel;  
    }  
      
    public void onMarkerSelect(OverlaySelectEvent event) {  
        Marker marker = (Marker) event.getOverlay();  
          
        //addMessage(new FacesMessage(FacesMessage.SEVERITY_INFO, "Marker Selected", marker.getTitle()));
        FacesContext context = FacesContext.getCurrentInstance();  
          
        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Marker Selected", marker.getTitle()));  
        
    }  
    

    public static double getLatitude() {
        return latitude;
    }

    public static void setLatitude(double latitude) {
        MapBean.latitude = latitude;
    }

    public static double getLongitude() {
        return longitude;
    }

    public static void setLongitude(double longitude) {
        MapBean.longitude = longitude;
    }

    public static String getDescriptionPOI() {
        return descriptionPOI;
    }

    public static void setDescriptionPOI(String descriptionPOI) {
        MapBean.descriptionPOI = descriptionPOI;
    }

    public static String urlGenerater(String adresse)
    {
        String adrTrim = adresse.trim();
        String adrReplace = adrTrim.replace(" ", "+");
        return adrReplace;
    }
    
    public static String yahooLatLong(String adr, String ville, String pays)
    {
        String latitude_yahoo="";
        String longitude_yahoo="";
        try {    
            
            //String  adr = urlGenerater(MapBean.adressePOI);
            //String  ville = urlGenerater(MapBean.villePOI);
            //String  pays = urlGenerater(MapBean.paysPOI);
            
            System.out.println("yahoo adr "+adr);
            System.out.println("yahoo ville "+ville);
            System.out.println("yahoo pays "+pays);
            
            String url = "http://where.yahooapis.com/geocode?location="+urlGenerater(adr)+","+urlGenerater(ville)+","+urlGenerater(pays);
            HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
            con.setRequestMethod("GET");
            con.connect();
            System.out.println("Response Code "+con.getResponseMessage()); // test affiche
            InputStream is = con.getInputStream();
            
            DocumentBuilder parser;
            parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = parser.parse(is);
            System.out.println("Document "+doc.getXmlVersion());
            NodeList nodeList = doc.getChildNodes();
            System.out.println("Node name lvl 0 "+nodeList.item(0).getNodeName());//Noeud unique, ResultSet
            System.out.println("Node name lvl 1 "+nodeList.item(0).getChildNodes().item(5).getNodeName()); //Noeud fils unique, Result
            System.out.println("Node name lvl 2 "+nodeList.item(0).getChildNodes().item(5).getChildNodes().item(1).getNodeName()+" -- "+nodeList.item(0).getChildNodes().item(5).getChildNodes().item(1).getTextContent());//Latitude
            System.out.println("Node name lvl 2 "+nodeList.item(0).getChildNodes().item(5).getChildNodes().item(2).getNodeName()+" -- "+nodeList.item(0).getChildNodes().item(5).getChildNodes().item(2).getTextContent());//Longitude
            for(int i=0;i<nodeList.getLength();i++)
              {
                  if(nodeList.item(i).getNodeName().equals("ResultSet"))
                  {
                      NodeList nodeListLvl1 = nodeList.item(i).getChildNodes();
                      for(int j=0;j<nodeListLvl1.getLength();j++)
                      {
                          if(nodeListLvl1.item(j).getNodeName().equals("Result"))
                          {
                              NodeList nodeListLvl2 = nodeListLvl1.item(j).getChildNodes();
                              for(int k=0;k<nodeListLvl2.getLength();k++)
                              {
                                  if(nodeListLvl2.item(k).getNodeName().equals("latitude"))
                                  {
                                      latitude_yahoo = nodeListLvl2.item(k).getTextContent();
                                  }
                                  if(nodeListLvl2.item(k).getNodeName().equals("longitude"))
                                  {
                                      longitude_yahoo = nodeListLvl2.item(k).getTextContent();
                                  }
                              }
                          }
                      }
                  }
              }
           
          System.out.println("LATITUDE "+latitude_yahoo);  
          System.out.println("LONGITUDE "+longitude_yahoo);  
          
        } catch (SAXException ex) {
            Logger.getLogger(MapBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(MapBean.class.getName()).log(Level.SEVERE, null, ex);
            
        } catch (MalformedURLException ex) {
            Logger.getLogger(MapBean.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MapBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return latitude_yahoo+"-"+longitude_yahoo;
    }
   
    
    public static void enseigneCoor(Enseigne e)
    {
       setLatitude(e.getLatitude());
       setLongitude(e.getLongitude());
       setDescriptionPOI(e.getDescription());
    }
}
